<?php


	// 连接数据库
	include("conn.php");
	include("functions.php");

	// 接收参数
	$table = $_POST["table"]; // 表名
	$do = $_POST["do"]; // 操作：insert 新增； update 修改； delete 删除
	$fields = isset($_POST["fields"]) ? $_POST["fields"] : "";  // 字段列表键值对，在新增和修改中必要提供
	$conditions = isset($_POST["conditions"])? $_POST["conditions"] : ""; // 条件列表健值对，在修改和删除中必要提供

	// 处理参数
	if($do == 'insert'){  // insert 需要参数：table， do， fields
		$fieldsName = array();
		$fieldsValue = array();
		foreach (json_decode($fields, false) as $key => $value) {
			array_push($fieldsName, $key);
			array_push($fieldsValue, "'" . $value . "'");
		}

		$fieldsNameStr = join(",", $fieldsName);
		$fieldsValueStr = join(",", $fieldsValue);

		$sql = "INSERT INTO $table ( $fieldsNameStr ) VALUES ( $fieldsValueStr ) ";

		// 执行sql
		$rs = $conn->exec($sql) or die($sql);
		echo $conn->lastInsertId();
	}

	if($do == 'update'){  // update 需要参数： table， do， fields， conditions
		$updatesList = array();
		foreach (json_decode($fields, false) as $key => $value) {
			array_push($updatesList, $key . "='" . $value . "'");
		}
		$updatesListStr = join(",", $updatesList);
		$conditionsList = array();
		foreach (json_decode($conditions, false) as $key => $value) {
			array_push($conditionsList, $key . "='" . $value . "'");
		}
		$conditionsListStr = join(" and ", $conditionsList);

		$sql = "UPDATE $table SET $updatesListStr WHERE $conditionsListStr ";

		$rs = $conn->exec($sql) or die($sql);
		echo $rs;
	}

	if($do == 'delete'){ // delete 需要参数： table， do， conditions
		$conditionsList = array();
		foreach (json_decode($conditions, false) as $key => $value) {
			array_push($conditionsList, $key . "='" . $value . "'");
		}
		$conditionsListStr = join(" and ", $conditionsList);

		$sql = "DELETE FROM $table WHERE $conditionsListStr ";

		$rs = $conn->exec($sql) or die($sql);
		echo $rs;
	}

	if($do == 'select'){ // select 需要参数： table， do，fields, conditions
		if($conditions){
			$conditionsList = array();
			foreach (json_decode($conditions, false) as $key => $value) {
				array_push($conditionsList, $key . "='" . $value . "'");
			}
			$conditionsListStr = join(" and ", $conditionsList);
		} else{
			$conditionsListStr = "true";
		}
		if($fields){
			$fieldsStr = $fields;
		} else{
			$fieldsStr = "*";
		}

		$sql = " SELECT $fieldsStr FROM $table WHERE $conditionsListStr";

		echo query_sql($sql, $conn);
	}


	if($do == 'like'){ // like 需要参数： table， do，fields, conditions, 其中conditions 按like匹配
		if($conditions){
			$conditionsList = array();
			foreach (json_decode($conditions, false) as $key => $value) {
				array_push($conditionsList, $key . " like '%" . $value . "%'");
			}
			$conditionsListStr = join(" and ", $conditionsList);
		} else{
			$conditionsListStr = "true";
		}
		if($fields){
			$fieldsStr = $fields;
		} else{
			$fieldsStr = "*";
		}

		$sql = " SELECT $fieldsStr FROM $table WHERE $conditionsListStr";

		echo query_sql($sql, $conn);
	}


?>